package com.anita.member.common.config;

import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 图片上传自动配置类
 * @author qiu
 * @date 2025/10/22
 * @description
 */
@Configuration
@EnableConfigurationProperties({
        ImageUploadProperties.class,
        QiniuConfig.class
})
@AllArgsConstructor
@ComponentScan(basePackages = "com.anita.member.common.config")
public class ImageUploadAutoConfiguration {
    private final QiniuConfig qiniuConfig;

    /**
     * 配置七牛云认证
     */
    @Bean(name = "qiniuAuth")
    @ConditionalOnProperty(name = "image.upload.type", havingValue = "qiniu")
    public Object qiniuAuth() {
        if (!qiniuConfig.isValid()) {
            throw new IllegalArgumentException("七牛云配置不完整，请检查accessKey和secretKey配置");
        }

        try {
            Class<?> authClass = Class.forName("com.qiniu.util.Auth");
            return authClass.getMethod("create", String.class, String.class)
                    .invoke(null, qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        } catch (Exception e) {
            throw new RuntimeException("创建七牛云认证失败", e);
        }
    }

    /**
     * 配置七牛云上传管理器
     */
    @Bean(name = "qiniuUploadManager")
    @ConditionalOnProperty(name = "image.upload.type", havingValue = "qiniu")
    public Object qiniuUploadManager() {
        try {
            // 构造一个带指定Zone对象的配置类
            Class<?> regionClass = Class.forName("com.qiniu.storage.Region");
            Object autoRegion = regionClass.getMethod("autoRegion").invoke(null);

            Class<?> configClass = Class.forName("com.qiniu.storage.Configuration");
            Object cfg = configClass.getConstructor(regionClass).newInstance(autoRegion);

            Class<?> uploadManagerClass = Class.forName("com.qiniu.storage.UploadManager");
            return uploadManagerClass.getConstructor(configClass).newInstance(cfg);
        } catch (Exception e) {
            throw new RuntimeException("创建七牛云上传管理器失败", e);
        }
    }
}
